/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Login.java
 *
 * Created on Mar 29, 2011, 10:42:27 AM
 */

package Project2.cs342.project1.mathNotebook.gui;

import Project2.cs342.project1.mathNotebook.Database.DBUsers;
import Project2.cs342.project1.mathNotebook.data.User;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Rick
 */
public class Login extends javax.swing.JFrame {

    /** Creates new form Login */
    public Login() {
        initComponents();
    }
    public String username;

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        usernameLabel = new javax.swing.JLabel();
        passwordLabel = new javax.swing.JLabel();
        userNameTextField = new javax.swing.JTextField();
        loginButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        passwordField = new javax.swing.JPasswordField();
        createNewUserLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login");
        setBounds(new java.awt.Rectangle(400, 200, 0, 0));

        usernameLabel.setText("Username");

        passwordLabel.setText("password");

        userNameTextField.setNextFocusableComponent(passwordField);

        loginButton.setText("Login");
        loginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        passwordField.setNextFocusableComponent(loginButton);

        createNewUserLabel.setText("Create New User");
        createNewUserLabel.setAlignmentX(300.0F);
        createNewUserLabel.setAlignmentY(200.0F);
        createNewUserLabel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        createNewUserLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                createNewUserLabelMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(usernameLabel)
                            .addComponent(passwordLabel))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(userNameTextField)
                            .addComponent(passwordField, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(cancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(loginButton, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)))
                    .addComponent(createNewUserLabel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usernameLabel)
                    .addComponent(userNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(loginButton))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passwordLabel)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cancelButton))
                .addGap(18, 18, 18)
                .addComponent(createNewUserLabel)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void createNewUserLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_createNewUserLabelMouseClicked
        CreateNewUser newUser = new CreateNewUser();
        newUser.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_createNewUserLabelMouseClicked

    private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed

        DBUsers dbUsers = new DBUsers();
        boolean correctLogin = false;

	if(userNameTextField.getText().equals("") || passwordField.getText().equals("")){

	    JOptionPane.showMessageDialog(this, "Please fill in both fields.",
						"Login Error", JOptionPane.ERROR_MESSAGE);
	}
	else{
	    
	    correctLogin = dbUsers.checkLogin(userNameTextField.getText().trim(),
						    passwordField.getText().trim());

	    if(correctLogin){
		User user = populateUser(dbUsers);
		UserInterface mainContent = new UserInterface(user);
		mainContent.setVisible(true);
                mainContent.username = username;
		this.dispose();
	    }else{
		JOptionPane.showMessageDialog(this, "Incorrect Username / Password",
						"Login Error", JOptionPane.ERROR_MESSAGE);
	    }
	}
    }//GEN-LAST:event_loginButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        System.exit(1);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private User populateUser(DBUsers dBUsers){
        
            FileInputStream fis = null;
            File file = null;
            User user = new User();
            String userName = userNameTextField.getText().trim();
            this.username = userName;
            user.setUsername(userName);
            user.setPassword(passwordField.getText().trim());
        try {
            dBUsers.retrieveRSAPublicKey(userName);
            file = new File("public.txt");
            fis = new FileInputStream(file);
            byte[] rsaPublicKey = new byte[(int) file.length()];
            fis.read(rsaPublicKey);
            user.setRsaPublicKey(rsaPublicKey);

            dBUsers.retrieveRSAPrivateKey(userName);
            file = new File("private.txt");
            fis = new FileInputStream(file);
            byte[] rsaPrivateKey = new byte[(int) file.length()];
            fis.read(rsaPrivateKey);
            user.setRsaPrivateKey(rsaPrivateKey);

            dBUsers.retrieveDESKey(userName);
            file = new File("localDes.txt");
            fis = new FileInputStream(file);
            byte[] localDesKey = new byte[(int) file.length()];
            fis.read(localDesKey);
            String fileContent = new String(localDesKey);
            user.setDesDefaultKey(fileContent);
            
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch(IOException ex){
            ex.printStackTrace();
        }

        return user;
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Login().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel createNewUserLabel;
    private javax.swing.JButton loginButton;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JTextField userNameTextField;
    private javax.swing.JLabel usernameLabel;
    // End of variables declaration//GEN-END:variables

}
